<template>
  <div class="editPurchase">
    <div class="dropdown">
      <jc-button
        :btn-arr="['save', 'remove', 'pass', 'sub', 'option', 'reload', 'list']"
        :disab-arr="[isDisabled && 'save', 'close', 'cancel', 'toExcel', 'using', 'com1', 'com2', 'freeze']"
        :fbillno="prodValue.fbillNo"
        :list="'/qualityList'"
        @refresh="queryTSalOrderNtry"
        @save="insert('A', 1)"
        @submit="insert('A', 1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @del="delPurchase"
      />
    </div>
    <el-tabs v-model="activeName" class="tabs" @tab-click="handleClick">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form ref="purchaseRef" :model="prodValue" label-width="100px">
          <el-form-item :label="$t('market.state')" prop="fdocumentStatus">
            <el-tag
              :type="prodValue.stateColor"
            >
              {{ prodValue.fdocumentStatus }}
            </el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.billType')" prop="fbilltype">
            <el-input
              v-model.trim="prodValue.fbilltype"
              size="mini"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model="prodValue.fbillNo" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.fdate')" prop="fdeliveryDate">
            <el-date-picker
              v-model="prodValue.fdate"
              type="date"
              value-format="yyyy-MM-dd"
              size="mini"
              :disabled="isDisabled"
              :placeholder="$t('market.checkDate')"
              style="width: 163px"
            />
          </el-form-item>
          <el-form-item :label="$t('market.checkouttype')">
            <el-input v-model="prodValue.fcheckouttype" disabled size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.dutydept')">
            <el-input v-model="prodValue.fdutydept" size="mini">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="departVisiblit=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.dutyer')">
            <el-input v-model="prodValue.fdutyer" size="mini">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="departRenVisiblit=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.note')" prop="fdescription">
            <el-input
              v-model.trim="prodValue.fdescription"
              :disabled="isDisabled"
              placeholder="请填写备注"
              size="mini"
            />
          </el-form-item>
        </el-form>
        <div style="margin: 10px 0 5px;">
          <el-button size="mini" :disabled="isDisabled" @click="newLine">{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <el-button size="mini" :disabled="isDisabled" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button size="mini" :disabled="isDisabled" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
        </div>
        <div>
          <!--明细表格-->
          <jc-table
            :table-data="saleDetails"
            :table-header="tableHeader"
            serial
            :table-height="tableHeight"
            @cellClick="cellClick"
            @rowClick="rowClick"
          >
            <el-table-column type="selection" width="30px" sortable="true" align="center" />
            <el-table-column v-if="prodValue.fcheckouttype !== 'IQC'" :label="$t('menu.collect')" prop="fsrcbillno" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fsrcbillno" size="mini" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="scOrder(scope.$index)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column v-if="prodValue.fcheckouttype === 'IQC'" label="采购订单" align="center" prop="fsrcbillno" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fsrcbillno" size="mini" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="cgOrder(scope.$index)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.fmaterial')" align="center" width="150" prop="fnumber">
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.fnumber"
                  placeholder="请选择物料"
                  size="mini"
                  :disabled="isDisabled"
                  @input="getAtuo(scope.$index, scope.row.fnumber)"
                >
                  <i
                    slot="prefix"
                    class="iconfont icon-jin-rud-ao-bo"
                    @click="sonJumpMateriel(scope.row.fnumber)"
                  />
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="materia(scope.$index)"
                  />
                </el-input>
                <div v-if="aotuTab && indexSelf === scope.$index" :class="indexSelf<7 ? 'tabPosit': 'tabPosit1'">
                  <number-code :fnumber="fnumber" @material="materialData" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.fmodel')" prop="fmodel" align="center" show-overflow-tooltip />
            <el-table-column :label="$t('shop.fname2')" prop="fname" align="center" show-overflow-tooltip />
            <el-table-column :label="$t('shop.fspecificaTion')" prop="fspecificaTion" align="center" show-overflow-tooltip />
            <el-table-column :label="$t('market.fdescripTion')" prop="fdescripTion" align="center" min-width="200" show-overflow-tooltip />
            <el-table-column :label="$t('market.checkunit')" prop="funit" align="center" />
            <el-table-column :label="$t('market.checkqty')" align="center" prop="fcheckqty">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fcheckqty"
                  :min="0"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.heqty')" align="center" prop="fheqty">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fheqty"
                  :min="0"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.checkway')" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.fcheckwayid"
                  size="mini"
                  clearable
                  :disabled="isDisabled"
                >
                  <el-option v-for="item in storeData2" :key="item.fid" :label="item.fname" :value="item.fid" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.result')" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.fresultid"
                  size="mini"
                  clearable
                  :disabled="isDisabled"
                >
                  <el-option v-for="item in storeData" :key="item.fid" :label="item.fname" :value="item.fid" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.errReason')" align="center" width="120">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.freasonid"
                  size="mini"
                  clearable
                  :disabled="isDisabled"
                >
                  <el-option v-for="item in storeData1" :key="item.fid" :label="item.fname" :value="item.fid" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.inWorkshop')" align="center" width="120">
              <template slot-scope="scope">
                <el-autocomplete
                  v-model.trim="scope.row.fworkshop"
                  highlight-first-item
                  popper-class="my-autocomplete"
                  :fetch-suggestions="querySearch8"
                  size="mini"
                  :disabled="isDisabled"
                  @focus="getBasicUnit('SX_V_WORKSHOP', scope.$index)"
                  @select="selUnit"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="cliUnit('SX_V_WORKSHOP', scope.$index)"
                  />
                  <template slot-scope="{ item }">
                    <div class="name">{{ item.fname }}</div>
                  </template>
                </el-autocomplete>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.zedept')" align="center" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fzedept" size="mini" :disabled="isDisabled">
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="zrdept(scope.$index)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.cost')" align="center" width="50">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.fiscost" :disabled="isDisabled" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.productamount')" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.fproducefamount"
                  :min="0"
                  :disabled="!scope.row.fiscost && !isDisabled"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.paezText1')" align="center" width="120">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.fpaeztext"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.note')" align="center" width="120">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.fnote"
                  size="mini"
                  :disabled="isDisabled"
                />
              </template>
            </el-table-column>
            <el-table-column :label="$t('market.handle')" align="center">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="mini"
                  :disabled="isDisabled"
                  @click="handleDelete(scope.$index)"
                >{{ $t('shop.delete') }}
                </el-button>
              </template>
            </el-table-column>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="prodValue.fbillNo"
          other-height="68vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--    物料弹窗-->
    <material v-if="isMateria" :qc="prodValue.fcheckouttype" :fid="scFid" @material="materialData" />
    <!--责任部门-->
    <responDepart v-if="departVisiblit" @depart="departData" />
    <!--责任人-->
    <responRen v-if="departRenVisiblit" :msg="prodValue.fdutydeptid" @depart="departData1" />
    <!--  数据字典弹窗  -->
    <unit v-if="unitVisabled" :msg="funit" @unit="selUnit" />
    <!--生产订单-->
    <product v-if="productVisiblit" @product="productData" />
    <!--采购订单-->
    <purchase v-if="purchaseVisiblit" @product="purchaseData" />
  </div>
</template>
<script>
import {
  purCheckUnAudit, purMrbAudit,
  purCheckAuSubmit, purCheckSubmit,
  purCheckDelete, queryPurCheckDetails,
  updatePurCheck
} from '@/api/quality/index'
import jumpMateriel from '@/components/JumpMateriel'
import mixinsImg from '@/views/market/marketManage/createMarkerOrder/components/mixinsImg'
import { toMxAmina } from '@/components/ToMxamineState'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import jcButton from '@/components/Button'
import jcMarker from '@/components/marker'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import responDepart from '@/views/quality/qualityDetail/component/responDepart'
import responRen from '@/views/quality/qualityDetail/component/responRen'
import product from '@/views/quality/qualityDetail/component/product'
import purchase from '@/views/quality/qualityDetail/component/purchase'
export default {
  name: 'QualityDetail',
  components: {
    jcMarker,
    jcButton,
    unit: () => import('@/views/basic/createMateriel2/components/unit'),
    responDepart,
    responRen,
    product,
    material: () => import('@/views/market/marketManage/createMarkerOrder/components/material'),
    purchase,
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [jumpMateriel, mixinsImg, autocomplete],

  data() {
    return {
      aotuTab: false,
      fnumber: '',
      funit: '',
      activeName: 'first', // 基本信息
      unitVisabled: false, // 字典
      departVisiblit: false, // 责任部门
      departRenVisiblit: false, // 责任人
      prodValue: {}, // 表单数据
      tableHeight: 'calc(100vh - 290px)',
      isMateria: false,
      productVisiblit: false,
      purchaseVisiblit: false,
      indexSelf: 0,
      saleDetails: [],
      tableHeader: [],
      indexDept: -1,
      pageNum: 1,
      size: 10,
      total: 0,
      otherUrlObject: {},
      gys: '',
      scFid: 0,
      storeData: [],
      storeData1: [],
      storeData2: [],
      isDisabled: false // 是否禁止输入
    }
  },
  created() {
    if (this.$route.params.id) {
      this.queryTSalOrderNtry() // 获取订单列表数据
      this.getBasicUnit() // 检验结果
      this.getBasicUnit1() // 异常原因
      this.getBasicUnit2() // 检验方式
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 290px)' : '66vh'
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.indexSelf = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber = fnumber
      }, 600)
    },
    // 检验结果 (数据字典公共接口)
    async getBasicUnit() {
      const DATA = { viewName: 'SX_RESULTID' }
      const { data: RES } = await queryViewItem(DATA)
      this.storeData = RES.list
    },
    // 异常原因 (数据字典公共接口)
    async getBasicUnit1() {
      const DATA = { viewName: 'SX_RESULT' }
      const { data: RES } = await queryViewItem(DATA)
      this.storeData1 = RES.list
    },
    // 检验方式 (数据字典公共接口)
    async getBasicUnit2() {
      const DATA = { viewName: 'SX_CHECKWAYID' }
      const { data: RES } = await queryViewItem(DATA)
      this.storeData2 = RES.list
    },
    // 修改品质检验单
    async insert(ev, en) {
      this.prodValue.details = this.saleDetails
      const DATA = {
        ...this.prodValue,
        fdocumentStatus: ev
      }
      await updatePurCheck(DATA).then(res => {
        if (res.code === 0) {
          en === 1 ? this.submit(1) : this.queryTSalOrderNtry()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
      })
    },
    // 获取订单列表数据
    async queryTSalOrderNtry() {
      const id = this.$route.params.id
      const DATA = { fid: id }
      const { data: RES } = await queryPurCheckDetails(DATA)
      this.prodValue = toMxAmina(RES)
      this.otherUrlObject = RES
      this.isDisabled = this.prodValue.fdocumentStatus === this.$t('market.state1') || this.prodValue.fdocumentStatus === this.$t('market.state2')
      this.saleDetails = RES.details
    },
    // 打开物料弹窗
    materia(index) {
      this.isMateria = true
      this.indexSelf = index
    },
    // 获取物料
    materialData(ev) {
      if (ev.fnumber) {
        const item = this.saleDetails[this.indexSelf]
        item.fmodel = ev.fmodel
        item.fnumber = ev.fnumber
        item.fname = ev.fname
        item.fmaterialId = ev.fmaterialId
        item.fspecificaTion = ev.fspecificaTion
        item.fdescripTion = ev.fdescripTion
        item.funit = ev.funit
        item.fsrcid = ev.fsrcid
        item.fsrcbillno = ev.fsrcbillno
        item.fsrcentryid = ev.fsrcentryid
        item.fsrcentryseq = ev.fsrcentryseq
        item.fsrcbilltype = ev.fsrcbilltype
      }
      this.isMateria = false
    },
    zrdept(index) {
      this.indexDept = index
      this.departVisiblit = true
    },
    // 责任部门
    departData(ev) {
      if (ev.fid && this.indexDept === -1) {
        this.prodValue.fdutydept = ev.fname
        this.prodValue.fdutydeptid = ev.fid
      } else if (ev.fid) {
        const item = this.saleDetails[this.indexDept]
        item.fzedeptid = ev.fid
        item.fzedept = ev.fname
        this.indexDept = -1
      }
      this.departVisiblit = false
    },
    // 责任人
    departData1(ev) {
      if (ev.fuserId) {
        this.prodValue.fdutyer = ev.fname
        this.prodValue.fdutyerid = ev.fuserId
        this.prodValue.fdutydept = ev.fprimaryGroupName
        this.prodValue.fdutydeptid = ev.fuserGroupId
      }
      this.departRenVisiblit = false
    },
    // 生产订单
    scOrder(index) {
      this.productVisiblit = true
      this.materielIndex = index
    },
    // 生产订单
    productData(ev) {
      if (ev.fid) {
        const item = this.saleDetails[this.materielIndex]
        item.fsrcbillno = ev.fbillNo
        this.scFid = ev.fid
      }
      this.productVisiblit = false
    },
    // 采购订单
    cgOrder(index) {
      this.purchaseVisiblit = true
      this.materielIndex = index
    },
    // 采购订单
    purchaseData(ev) {
      if (ev.fid) {
        const item = this.saleDetails[this.materielIndex]
        item.fsrcbillno = ev.fbillNo
        this.scFid = ev.fid
      }
      this.purchaseVisiblit = false
    },
    // 数据字典弹窗
    cliUnit(ev, index) {
      this.materielIndex = index
      this.funit = ev
      this.unitVisabled = true
    },
    // 数据字典选中
    selUnit(ev) {
      if (ev.fid) {
        if (this.funit === 'SX_V_WORKSHOP') { // 生产部门
          const item = this.saleDetails[this.materielIndex]
          item.fworkshop = ev.fname
          item.fworkshopid = ev.fid
        }
      }
      this.unitVisabled = false
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.prodValue.fbillNo] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.queryTSalOrderNtry()
      })
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? purCheckSubmit : purCheckAuSubmit
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? purMrbAudit : purCheckUnAudit
      this.toExamineFun(api)
    },
    // 删除
    delPurchase() {
      if (this.isDisabled) {
        this.$confirm('请先反审核后再删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      const DATA = {
        Numbers: [this.prodValue.fbillNo]
      }
      this.$confirm('确定要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        purCheckDelete(DATA).then(res => {
          if (res.code === 0) {
            // 关闭当前页面
            this.$store.dispatch('tagsView/guanbi', this.$route)
            this.$router.push({ path: '/qualityList' })
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
        })
      })
    },
    // 表格删除行
    handleDelete(index) {
      this.saleDetails.splice(index, 1)
    },
    // 新增行
    newLine() {
      const data = {
        fqty: 0,
        fmodel: '',
        fpaezText1: '',
        funit: '',
        fmaterialId: 0,
        fspecificaTion: '',
        funitId: 0,
        fstockQty: 0,
        sumInvQty: 0,
        fprice: 0,
        ftaxPrice: 0,
        fdescripTion: '',
        fdeliveryDate: new Date(),
        fnumber: '',
        fentryId: 0,
        fstockUnitId: 0,
        fiscost: false,
        fzedept: '',
        fsrcbillno: '',
        fworkshop: '',
        fproducefamount: 0
      }
      this.saleDetails.push(data)
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      this.saleDetails.splice(this.indexSelf, 1)
    },
    // 套打A4
    queryReportForm() {
      const FNUMBER = this.prodValue.fbillNo
      this.$router.push({ path: `/purOrderAsi/${FNUMBER}` })
    },
    // 套打 连打
    queryReportForm1() {
      const FNUMBER = this.prodValue.fbillNo
      this.$router.push({ path: `/purOrderLianDa/${FNUMBER}` })
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.saleDetails[this.subscript][this.property]
      const fworkshopid = this.saleDetails[this.subscript].fworkshopid
      this.saleDetails.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
          if (this.property === 'fworkshop') {
            res.fworkshopid = fworkshopid
          }
        }
      })
    },
    // 点击tabs
    handleClick(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    }
  }
}
</script>
<style scoped lang="scss">
.editPurchase {
  @include listBom;
  padding: 10px;
  .tabs{
    &::v-deep .el-tabs__content {
      min-height: calc(100vh - 180px)
    }
  }
  .el-tabs {
    &::v-deep.el-tabs__header {
      margin: 0 0 5px;
    }
    .el-input::v-deep .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
    .el-form {
      display: flex;
      flex-wrap: wrap;

      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        margin-bottom: 5px;
        .btnType{
          margin-right: 20px;
        }
        .el-date-editor.el-input{
          width: 100% !important;
        }
        .el-select{
          width: 100%;
        }
      }
    }
  }
}

.el-input__icon {
  cursor: pointer;
}

</style>
